﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProtocolBuilder.Model.Field
{
    class ComposeConditionField : ComposeField
    {
        public override string GenerateSerializeCode()
        {
            return this.GenerateCode(true);
        }

        public override string GenerateDeserializeCode()
        {
            return this.GenerateCode(false);
        }

        /// <summary>
        /// generate serialize or deserialize code for this field.
        /// </summary>
        /// <param name="serialize">indicate which style will use in the generated code,true is for serialize,otherwise deserialize.</param>
        /// <returns></returns>
        private string GenerateCode(bool serialize)
        {
            string whiteSpace = this.GenerateWhiteSpace();
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}switch(@pp){1}{0}{{{1}", whiteSpace, TextHelper.HtmlNewLine);

            IEnumerable<AbsField> children = this.GetChildrenField();
            foreach (AbsField child in children)
            {
                SingleConditionField condition = child as SingleConditionField;
                if (condition != null)
                {
                    sb.AppendFormat("{0}{1}case {2}://{3}{4}", whiteSpace, TextHelper.HtmlTab, condition.CaseValue, condition.Description, TextHelper.HtmlNewLine);
                    sb.Append(serialize ? condition.GenerateSerializeCode() : condition.GenerateDeserializeCode());
                    sb.AppendFormat("{0}{1}{1}break;{2}", whiteSpace, TextHelper.HtmlTab, TextHelper.HtmlNewLine);
                }
            }

            sb.AppendFormat("{0}}}", whiteSpace);

            return sb.ToString();
        }
    }
}